package org.fuse.prototype.common;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class LoggingTransformer implements ClassFileTransformer {

    @Override
    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {

        if (className.indexOf("/") != -1) {
            className = className.replaceAll("/", ".");
        }

        if (!"org.fuse.prototype.common.User".equals(className)) {
            return null;
        }
        
        try {

            CtClass ctClass = ClassPool.getDefault().get("org.fuse.prototype.common.User");
            String mname = "getProfile";
            CtMethod mold = ctClass.getDeclaredMethod(mname);

            String txt = "\nSystem.out.println(nameStr);\n";
            mold.insertAt(8, txt);

            mold.insertAt(9, "\nSystem.out.println(\"execute!....\");\n");

            String txt2 = "\nSystem.out.println(nameStr2);\n";
            mold.insertAt(11, txt2);

            String txt3 = "\nSystem.out.println(nameStr3);\n";
            mold.insertAt(15, true, txt3);
            
            return ctClass.toBytecode();
        } catch (NotFoundException e) {
        } catch (CannotCompileException e) {
            e.printStackTrace();
        } catch (IOException e) {
        }
        return null;
    }

}